package com.szpx.controller;

import com.szpx.entity.Goods;
import com.szpx.entity.Result;
import com.szpx.entity.TBUser;
import com.szpx.service.TBUserService;
import com.szpx.utils.BindingResultHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author June
 * @version 1.0.0
 * @title TBUserController
 * @create 2024/4/2 14:33
 * @description
 **/
@RestController
@RequestMapping("/tbUser")
public class TBUserController {
    @Autowired
    private TBUserService tbUserService;
    @Autowired
    private PlatformTransactionManager transactionManager; // 注入事务管理器

    /**
     * 从session中获取对象信息
     * @param request
     * @return
     */
    @GetMapping("/session")
    public TBUser sessionUser(HttpServletRequest request){
        return (TBUser) request.getSession().getAttribute("user");
    }

    /**
     * 注册
     *
     * @param tbUser
     * @param result
     * @return
     */
    @PostMapping("/register")
    public Result register(@Validated(TBUser.Register.class) TBUser tbUser, BindingResult result) {

        if (result.hasErrors()) {
            Map<String, String> map = BindingResultHelper.toErrorMap(result);
            return Result.error("参数错误");
        }

        boolean register = tbUserService.register(tbUser);
        return register ? Result.success("注册成功") : Result.error("注册失败");
    }

    /**
     * 根据ID查询
     *
     * @param uid
     * @return
     */
    @GetMapping("/{uid}")
    public Result<TBUser> selectByUid(@PathVariable(value = "uid") Integer uid) {
        return Result.success(tbUserService.selectByUid(uid));
    }

    /**
     * 用户账户管理修改用户email
     * @param requestData
     * @return
     */
    @PostMapping("/updateEmail")
    @ResponseBody
    public Result<String> updateUserEmail(@RequestBody Map<String, String> requestData) {
        String userId = requestData.get("uid");
        String newEmail = requestData.get("email");
        if (userId != null && newEmail != null) {
            TBUser tbUser = tbUserService.selectByUid(Integer.parseInt(userId));
            if (tbUser != null) {
                tbUser.setEmail(newEmail);
                tbUserService.updateUserEmail(tbUser);
                return Result.success("Email updated successfully");
            } else {
                return Result.error("User not found");
            }
        } else {
            return Result.error("Invalid input data");
        }
    }

    /**
     * 修改用户名
     * @param requestData
     * @return
     */
    @PostMapping("/updateUsername")
    @ResponseBody
    public Result<String> updateUsername(@RequestBody Map<String, String> requestData) {
        String userId = requestData.get("uid");
        String newUsername = requestData.get("username");
        if (userId != null && newUsername != null) {
            TBUser tbUser = tbUserService.selectByUid(Integer.parseInt(userId));
            if (tbUser != null) {
                tbUser.setUsername(newUsername); // 更新用户名属性为新用户名
                tbUserService.updateUserName(tbUser);
                return Result.success(newUsername); // 返回新的用户名信息
            } else {
                return Result.error("User not found");
            }
        } else {
            return Result.error("Invalid input data");
        }
    }

    /**
     * 修改手机号
     * @param requestData
     * @return
     */
    @PostMapping("/updatePhone")
    @ResponseBody
    public Result<String> updatePhone(@RequestBody Map<String, String> requestData) {
        String userId = requestData.get("uid");
        String newPhone = requestData.get("phone");
        if (userId != null && newPhone != null) {
            TBUser tbUser = tbUserService.selectByUid(Integer.parseInt(userId));
            if (tbUser != null) {
                tbUser.setPhone(newPhone); // 更新用户名属性为新用户名
                tbUserService.updateUserPhone(tbUser);
                return Result.success(newPhone); // 返回新的用户名信息
            } else {
                return Result.error("User not found");
            }
        } else {
            return Result.error("Invalid input data");
        }
    }

    /**
     * 登录
     *
     * @param tbUser
     * @param result
     * @param request 用于获取客户端请求的相关信息
     * @return
     */
    @PostMapping("/login")
    public Result login(@Validated(TBUser.Login.class) TBUser tbUser, BindingResult result, HttpServletRequest request) {

        /**
         * 如果匹配错误，则报错
         */
        if (result.hasErrors()) {
            Map<String, String> map = BindingResultHelper.toErrorMap(result);
            return Result.error("参数错误");
        }

        TBUser tbUser1 = tbUserService.login(tbUser);

        if (tbUser1 != null) {
            // 登录成功
            request.getSession().setAttribute("user", tbUser1);
            return Result.success("登录成功");
        } else {
            // 登陆失败
            return Result.error("手机号或密码错误");
        }
    }

    /**
     <<<<<<< HEAD
     * 查询全部用户信息
     * @return
     *//**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/loginOut")
    public Result logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return Result.success("已退出登录");
    }
    @GetMapping("/allUsers")
    public ResponseEntity<List<TBUser>> getAllUsers() {
        List<TBUser> users = tbUserService.findAll();
        return ResponseEntity.ok(users);
    }

    /**
     * 根据用户ID进行用户充值
     * @param userId 用户ID
     * @param amount 充值金额
     * @param request HTTP请求
     * @return ResponseEntity<Result<TBUser>> ResponseEntity包含Result和用户信息的响应实体
     */
    @PostMapping("/recharge/{uid}")
    public ResponseEntity<Result<TBUser>> recharge(@PathVariable(value = "uid") Integer userId, @RequestParam Double amount, HttpServletRequest request) {
        // 定义事务
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); // 设置事务隔离级别为Serializable
        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            // 根据用户ID查询用户信息
            TBUser user = tbUserService.selectByUid(userId);

            // 如果用户不存在，则返回错误信息
            if (user == null) {
                return ResponseEntity.ok(Result.error("用户ID不存在，无法进行充值"));
            }

            // 先从数据库中获取最新的用户信息
            user = tbUserService.selectByUid(userId);

            // 更新用户余额
            boolean success = tbUserService.updateUserBalance(userId, amount);

            if (success) {
                // 更新成功后，再次从数据库中获取用户信息
                user = tbUserService.selectByUid(userId);
                // 更新 session 中的用户信息
                request.getSession().setAttribute("user", user);
                // 提交事务
                transactionManager.commit(status);
                // 返回成功结果，包含用户信息
                return ResponseEntity.ok(Result.success(user));
            } else {
                // 充值失败，回滚事务
                transactionManager.rollback(status);
                return ResponseEntity.ok(Result.error("充值失败，请重试"));
            }
        } catch (Exception e) {
            // 发生异常，回滚事务
            transactionManager.rollback(status);
            return ResponseEntity.ok(Result.error("发生异常，请重试"));
        }
    }
}